﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Specifications;
using AppFramework.Codingrule.Exporting;
using AppFramework.DinosaursParkMes.BOM;
using AppFramework.DinosaursParkMes.CodingRuleModel;
using AppFramework.DinosaursParkMes.Material.Dto;
using AppFramework.DinosaursParkMes.ProductionPlanning.Dto;
using AppFramework.DinosaursParkMes.ProductionPlanningModel;
using AppFramework.DinosaursParkMes.TicketTask.DTO;
using AppFramework.Dto;
using AppFramework.TicketTask;
using AppFramework.WorkOrderModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design.Internal;
using NPOI.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace AppFramework.DinosaursParkMes.TicketTask
{
    /// <summary>
    /// 工单任务管理
    /// </summary>
    public class TicketTaskinfoAppService : AppFrameworkAppServiceBase, ITicketTaskinfoAppService
    {
        private readonly IRepository<TicketTaskinfo> repository;//工单任务表
        private readonly IRepository<ProductWorkModels> productionWordOrderrepository;//生产工单表
        private readonly IRepository<AppFramework.DinosaursParkMes.ProductionPlanningModel.ProductionPlanning> productionPlanningrepository;//生产计划表
        private readonly IRepository<AppFramework.DinosaursParkMes.BOM.BillOfMaterial> billOfMaterialrepository;//BOM主表
        private readonly IRepository<AppFramework.DinosaursParkMes.Process.CraftProcessModel> craftProcessModelrepository;//工艺路线子表
        private readonly IRepository<AppFramework.DinosaursParkMes.Process.ProcessModel> processModelrepository;//工序表
        private readonly IRepository<AppFramework.DinosaursParkMes.Process.CraftRouteModel> craftRouteModelrepository;//工艺路线主表
        private readonly IRepository<AppFramework.DinosaursParkMes.BOM.BillOfMaterialDetails> billOfMaterialDetailsrepository;//BOM字表
        private readonly IRepository<AppFramework.DinosaursParkMes.MaterialModel.Material> materialrepository;//物料表
        private readonly IMaterialExcelExporter materialExcelExporter;



        public TicketTaskinfoAppService(IRepository<TicketTaskinfo> repository, IRepository<ProductWorkModels> productionWordOrderrepository = null, IRepository<ProductionPlanningModel.ProductionPlanning> productionPlanningrepository = null, IRepository<BOM.BillOfMaterial> billOfMaterialrepository = null, IRepository<Process.CraftProcessModel> craftProcessModelrepository = null, IRepository<Process.ProcessModel> processModelrepository = null, IRepository<Process.CraftRouteModel> craftRouteModelrepository = null, IRepository<BillOfMaterialDetails> billOfMaterialDetailsrepository = null, IRepository<MaterialModel.Material> materialrepository = null, IMaterialExcelExporter materialExcelExporter = null)
        {
            this.repository = repository;
            this.productionWordOrderrepository = productionWordOrderrepository;
            this.productionPlanningrepository = productionPlanningrepository;
            this.billOfMaterialrepository = billOfMaterialrepository;
            this.craftProcessModelrepository = craftProcessModelrepository;
            this.processModelrepository = processModelrepository;
            this.craftRouteModelrepository = craftRouteModelrepository;
            this.billOfMaterialDetailsrepository = billOfMaterialDetailsrepository;
            this.materialrepository = materialrepository;
            this.materialExcelExporter = materialExcelExporter;
        }
        /// <summary>
        /// 工单任务显示
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet,Route("TicketTaskList")]
        public  async Task<PagedResultDto<TicketTaskinfoResponseDTO>> TicketTaskList(TicketTaskChaResponseDTO dto)
        {
            PagedResultDto<TicketTaskinfoResponseDTO> dtos = new PagedResultDto<TicketTaskinfoResponseDTO>();
            var renwu = repository.GetAll();
            var workorder = productionWordOrderrepository.GetAll();
            var productplan = productionPlanningrepository.GetAll();
            var bom = billOfMaterialrepository.GetAll();
            var gongyi = craftRouteModelrepository.GetAll();
            var gongyizi = craftProcessModelrepository.GetAll();
            var gongxu = processModelrepository.GetAll();
            var list = from a in repository.GetAll()
                       select new TicketTaskinfoResponseDTO
                       {
                           Id = a.Id,
                           Actualproductiontime = a.Actualproductiontime,
                           Completedate = a.Completedate,
                           CreationTime = a.CreationTime,
                           Missionnumber = a.Missionnumber,
                           Plannedproductiontime = a.Plannedproductiontime,
                           Plannedquantity = a.Plannedquantity,
                           Procedurenumber = gongyi.Where(m=>m.Routecoded==a.ProcessNumber).FirstOrDefault().Routecoded,//////
                           Processname = gongyizi.Where(m=>m.Craftcode== a.ProcessNumber).FirstOrDefault().Process,
                           Realquantity = a.Realquantity,
                           Runplantdate = a.Runplantdate,
                           Sitename = a.Sitename,
                           States = a.States,
                           Taskname = a.Taskname,
                           WorkOrderName =workorder.Where(m=>m.WorkOrderNumber==a.Workordernumber).FirstOrDefault().WorkOrderName,
                           Technologicalprocess = gongyi.Where(m=>m.Routecoded== a.ProcessNumber).FirstOrDefault().Routename,
                           PlanCode= workorder.Where(m => m.WorkOrderName == a.Workordernumber).FirstOrDefault().ExplainNumber,
                           //BOMCode = productplan.Where(m => m.Planningnumber == PlanCode).FirstOrDefault().BOMNumber,
                           Workordernumber =a.Workordernumber,
                       };
            if(!string.IsNullOrEmpty(dto.MissionNumber))
            {
                list = list.Where(m=>m.Missionnumber.Equals(dto.MissionNumber)||m.Taskname.Equals(dto.MissionNumber));
            }
            if(!string.IsNullOrEmpty(dto.WorkOrderNumber))
            {
                list = list.Where(m=>m.WorkOrderName.Equals(dto.WorkOrderNumber)||m.Workordernumber.Equals(dto.WorkOrderNumber));
            }
            if(!string.IsNullOrEmpty(dto.Processname))
            {
                list = list.Where(m=>m.Processname.Equals(dto.Processname));
            }
            if(dto.State!= TicketTaskEnum.All)
            {
                list = list.Where(m=>m.States.Equals(dto.State));
            }
            if(!string.IsNullOrEmpty(dto.Technologicalprocess))
            {
                list = list.Where(m => m.Technologicalprocess.Equals(dto.Technologicalprocess));
            }
            if(!string.IsNullOrEmpty(Convert.ToString(dto.CreationTinme)))
            {
                list = list.Where(m => m.CreationTime >= dto.CreationTinme);
            }
            if(!string.IsNullOrEmpty(Convert.ToString(dto.Completedate)))
            {
                list = list.Where(m => m.Completedate <= dto.Completedate);
            }
            if(!string.IsNullOrEmpty(Convert.ToString(dto.Runplantdate)))
            {
                list = list.Where(m=>m.Runplantdate>=dto.Runplantdate);
            }
            if(!string.IsNullOrEmpty(dto.Sitename))
            {
                list = list.Where(m=>m.Sitename.Equals(dto.Sitename));
            }
            dtos.TotalCount = list.Count();
            dtos.Items=await list.OrderByDescending(a=>a.Id).Skip((dto.pageindex-1)*dto.pagesize).Take(dto.pagesize).ToListAsync();
            return dtos;
        }
        /// <summary>
        /// 工单任务详情
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet,Route("TicketTaskSelect")]
        public async Task<TicketTaskSelectResponseDTO> TicketTaskSelect(string code)
        {
            var renwu = repository.GetAll();
            var workorder = productionWordOrderrepository.GetAll();
            var productplan = productionPlanningrepository.GetAll();
            var bom = billOfMaterialrepository.GetAll();
            var gongyi = craftRouteModelrepository.GetAll();
            var gongyizi = craftProcessModelrepository.GetAll();
            var gongxu = processModelrepository.GetAll();
            var bomzi = billOfMaterialDetailsrepository.GetAll();

            //var bomcode = productplan.Where(m => m.Planningnumber == workorder.Where(m => m.WorkOrderName == a).FirstOrDefault().ExplainNumber).FirstOrDefault().BOMNumber;

            var qqqq = repository.GetAll().FirstOrDefault(m => m.Missionnumber == code);
            var ppp = ObjectMapper.Map<TicketTaskSelectResponseDTO>(qqqq);
            ppp.ProductName = workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().ProductName;
            ppp.ProductCode = workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().WorkOrderNumber;
            ppp.Specification = workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().Specification;
            ppp.ProductTypeName = workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().ProductType;
            ppp.Units = workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().Unit;
            ppp.Technologicalprocess = gongyi.Where(m=>m.Routecoded==ppp.ProcessNumber).FirstOrDefault().Routename;
            ppp.WorkOrderName = workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().WorkOrderName;
            ppp.BOMCode = productplan.Where(m => m.Planningnumber == workorder.Where(m => m.WorkOrderNumber == ppp.Workordernumber).FirstOrDefault().ExplainNumber).FirstOrDefault().BOMNumber;
            ppp.children = new List<WuLiaoItem>();
            ppp.children = WuLiaoQingDan(ppp.BOMCode);
            return  ppp;
        }
        [HttpGet,Route("WuLiaoQingDan")]
        public List<WuLiaoItem> WuLiaoQingDan(string BOMNumber)
        {
            var bomzi = billOfMaterialDetailsrepository.GetAll().ToList();
            var wuliao = materialrepository.GetAll();
            var billOfMaterialDetailsModel = bomzi.Where(s => s.Numberbom.Equals(BOMNumber));
            List<WuLiaoItem> list=new List<WuLiaoItem>();
            foreach (var item in billOfMaterialDetailsModel)
            {
                var kkk = new WuLiaoItem();
                //查询BOM下关联的物料
                var materi = wuliao.Where(x => x.Materialnumber.Equals(item.Materialnumber)).FirstOrDefault();
                if (materi != null)
                {
                    
                    kkk = ObjectMapper.Map<WuLiaoItem>(materi);
                    kkk.Usageamount = item.Usageamount;
                    kkk.PracticalUsageamount = item.Usageamount - 1;
                    list.Add(kkk);
                }
                
            }
            return list;
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetFileTicketTask")]
        public async Task<FileDto> GetFileTicketTask()
        {
            var renwu = repository.GetAll();
            var workorder = productionWordOrderrepository.GetAll();
            var productplan = productionPlanningrepository.GetAll();
            var bom = billOfMaterialrepository.GetAll();
            var gongyi = craftRouteModelrepository.GetAll();
            var gongyizi = craftProcessModelrepository.GetAll();
            var gongxu = processModelrepository.GetAll();
            var list = from a in repository.GetAll()
                       select new TicketTaskinfoResponseDTO
                       {
                           Id = a.Id,
                           Actualproductiontime = a.Actualproductiontime,
                           Completedate = a.Completedate,
                           CreationTime = a.CreationTime,
                           Missionnumber = a.Missionnumber,
                           Plannedproductiontime = a.Plannedproductiontime,
                           Plannedquantity = a.Plannedquantity,
                           Procedurenumber = gongyi.Where(m => m.Routecoded == a.ProcessNumber).FirstOrDefault().Routecoded,//////
                           Processname = gongyizi.Where(m => m.Craftcode == a.ProcessNumber).FirstOrDefault().Process,
                           Realquantity = a.Realquantity,
                           Runplantdate = a.Runplantdate,
                           Sitename = a.Sitename,
                           States = a.States,
                           Taskname = a.Taskname,
                           WorkOrderName = workorder.Where(m => m.WorkOrderNumber == a.Workordernumber).FirstOrDefault().WorkOrderName,
                           Technologicalprocess = gongyi.Where(m => m.Routecoded == a.ProcessNumber).FirstOrDefault().Routename,
                           PlanCode = workorder.Where(m => m.WorkOrderName == a.Workordernumber).FirstOrDefault().ExplainNumber,
                           //BOMCode = productplan.Where(m => m.Planningnumber == PlanCode).FirstOrDefault().BOMNumber,
                           Workordernumber = a.Workordernumber,
                       };
            //获取表中所有的数据
            var query = await list.ToListAsync();
            ////获取物料分类数据
            var data = ObjectMapper.Map<List<TicketTaskOutPutDTO>>(query);
            data.ForEach(p =>
            {
                switch (p.States)
                {
                    case "NotWorkOrder":
                        p.States = "未派工";
                        break;
                    case "HaveBeenIssued":
                        p.States = "已下达";
                        break;
                    case "UnderWay":
                        p.States = "进行中";
                        break;
                    case "Finished":
                        p.States = "已完成";
                        break;
                    case "Closed":
                        p.States = "已关闭";
                        break;
                    case "Paused":
                        p.States = "已暂停";
                        break;
                }
            });
            var token = materialExcelExporter.TicketTaskFile(data);
            return token;
        }
    }
}
